package wht.jly.forum.config.security.authenticationhandler;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义认证成功处理器
 *
 * @author lanyangji
 * @date 2019/3/2 20:25
 */
@Component("securityAuthenticationSuccessHandler")
public class SecurityAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    /**
     * 认证成功后处理逻辑
     *
     * @param request
     * @param response
     * @param authentication
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        // 打印下登录成功的日志
        logger.info("用户【"+ServletRequestUtils.getStringParameter(request, "username") + "】登录成功.");

        // 移除session中的登录错误消息和用户登录信息
        request.getSession().removeAttribute(SecurityAuthenticationFailureHandler.LOGIN_FAILURE_MESSAGE);
        request.getSession().removeAttribute(SecurityAuthenticationFailureHandler.USER_LOGIN_INFO);

        super.onAuthenticationSuccess(request, response, authentication);
    }
}
